//
//  HeartRateProgressCell.swift
//  DaRings
//
//  Created by HFY on 2022/11/21.
//

import UIKit
import MYModule

class HeartRateStateCell: TableViewCell {
    
    var detail: SingleHeartRateDetailModel? {
        
        didSet {
            
            dataLabel.text = detail?.heartRateModel.heartRate.normalTitle
            dateLabel.text = detail?.heartRateModel.date.localString
            
            guard let detail = detail else {
                return
            }
            stateView.maxHeartRate = detail.maxHeartRate
            stateView.progressArray = detail.progressArray.map { Int($0) }
            
            stateView.heartRate = detail.heartRateModel.heartRate
            
            
            
        }
        
    }
    
    let stateView = HeartRateStateView()
    
    
    override func makeUI() {
        super.makeUI()
        contentView.backgroundColor =  UIColor.darkBackground
        
        let bgView = View()
        bgView.cornerRadius = 18.0
        bgView.backgroundColor = UIColor.background
        
        let topView = View()
        topView.backgroundColor = UIColor.background

        let dataStack = StackView()
        dataStack.axis = .horizontal
        dataStack.alignment = .lastBaseline
        dataStack.contentMode = .center
        dataStack.addArrangedSubview(dataLabel)
        dataStack.addArrangedSubview(unitLabel)
        let labelStackView = StackView()
        labelStackView.axis = .vertical
        labelStackView.alignment = .center
        
        contentView.addSubview(topView)
        contentView.addSubview(bgView)
        bgView.addSubview(labelStackView)
        bgView.addSubview(stateView)
        
        labelStackView.addArrangedSubview(dataStack)
        labelStackView.addArrangedSubview(dateLabel)
        
        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(36)
        }
        
        bgView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
        
        
        labelStackView.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(10)
            make.centerX.equalToSuperview()
        }
        
        
        
        stateView.snp.makeConstraints { make in
            make.top.equalTo(labelStackView.snp.bottom).offset(30)
            make.left.equalTo(26)
            make.right.equalTo(-26)
            make.bottom.equalToSuperview().offset(-30)
        }
        
        
    }
    
    private lazy var dataLabel: Label = {
        let label = Label.init()
        label.text = "--"
        label.font = Fonts.systemFont(ofSize: 40)
        return label
    }()
    
    private lazy var dateLabel: Label = {
        let label = Label.init()
        label.text = "--"
        label.font = Fonts.systemFont(ofSize: 11)
        return label
    }()
    
    private lazy var unitLabel: Label = {
        let label = Label.init()
        label.text = "heart_rate_bpm".language
        label.font = Fonts.systemFont(ofSize: 11)
        return label
    }()
    
}

extension HeartRateStateCell {
    
    class HeartRateStateView: View {
        
        public var maxHeartRate: Int = 220
        
        public var progressArray: [Int] = [117, 135, 154, 174] {
            
            didSet {
                
                progressLabels.enumerated().forEach { i, label in
                    
                    if i < progressArray.count {
                        let value = progressArray[i]
                        label.text = "\(value)"
                    }
                }
            }
            
        }
        
        public var heartRate: Int? {
            
            didSet {
                                
                guard let heartRate = heartRate else {
                    
                    markImageView.isHidden = true
                    return
                }
                markImageView.isHidden = false // heartRate == 0
                
                
                self.setNeedsDisplay()
                
            }
        }
        
        // 比例
        private var multiplied: CGFloat {
            
            guard let heartRate = heartRate else {
                return 0
            }

            var multiplied: CGFloat = 0
            
            for (i, progressHeartRate) in progressArray.enumerated() {
                if heartRate > progressHeartRate  {
                   
                    multiplied += equaltoLefts[i]
                    
                } else {
                    var lastObj = 0
                    if i - 1 >= 0 {
                        lastObj = progressArray[i - 1]
                    }
                    multiplied += CGFloat(heartRate - lastObj)/CGFloat(progressHeartRate - lastObj) * equaltoLefts[i]
                    
                    break
                }
            }
            
            
            
            return multiplied
            
        }
        
        private let equaltoLefts = [0.2, 0.2, 0.2, 0.2, 0.2]
        
        let markImageView = ImageView()
        
        let stateColorsView = StateColorsView()
        
        lazy var dottedLines: [DottedLine] = {
            
            var dottedLines: [DottedLine] = []
            
            (0..<4).forEach {_ in
                let line = DottedLine()
                dottedLines.append(line)
            }
            
            return dottedLines
        }()
        
        lazy var stateLabels: [Label] = {
            
            let stateLabels: [Label] = [
                "heart_rate_light".language,
                "heart_rate_weight".language,
                "heart_rate_aerobic".language,
                "heart_rate_anaerobic".language,
                "heart_rate_max".language,
            ].map({
                
                let label = Label()
                label.text = $0
                label.textColor = UIColor.assist_222222
                label.font = Fonts.systemFont(ofSize: 10)
                label.textAlignment = .center
                
                return label
            })
            
            return stateLabels
        }()
        
        lazy var progressLabels: [Label] = {
            
            let progressLabels: [Label] = progressArray.map({
                
                let label = Label()
                label.text = "\($0)"
                label.textColor = UIColor.assist_D0D0D0
                label.font = Fonts.systemFont(ofSize: 10)
                return label
            })
            
            return progressLabels
        }()
        
        override func makeUI() {
            super.makeUI()
            
            markImageView.layer.cornerRadius = 10
            markImageView.image = UIImage(named: "ic_home_today_hr_progress")
            markImageView.isHidden = true
            
            addSubview(stateColorsView)
            stateColorsView.addSubview(markImageView)
            
            progressLabels.forEach {
                self.addSubview($0)
            }
            
            stateLabels.forEach {
                self.addSubview($0)
            }
            
            dottedLines.forEach {
                self.addSubview($0)
            }
            
            stateColorsView.snp.makeConstraints { make in
                make.top.left.right.equalToSuperview()
                make.height.equalTo(24)
            }
            
            markImageView.snp.makeConstraints { make in
                make.left.equalToSuperview()
                make.centerY.equalToSuperview()
                
            }
            
            
            var beforeStateLabel: Label? = nil
            stateLabels.enumerated().forEach { i, label  in
                
                let multipliedOfLeft = self.equaltoLefts[i]
                label.snp.makeConstraints { make in
                    make.top.equalTo(stateColorsView.snp.bottom).offset(4)
                    if beforeStateLabel == nil {
                        
                        make.left.equalToSuperview()
                        
                    } else {
                        
                        make.left.equalTo(beforeStateLabel!.snp.right)
                    }
                    
                    make.width.equalTo(self.snp.width).multipliedBy(multipliedOfLeft)
                    
                    make.bottom.equalToSuperview()
                    
                }
                
                
                beforeStateLabel = label
            }
            
            
            
            progressLabels.enumerated().forEach {i, label  in
                
                label.snp.makeConstraints { make in
                    
                    make.top.equalTo(stateColorsView.snp.bottom).offset(4)
                    
                    let line = dottedLines[i]
                    make.centerX.equalTo(line.snp.centerX)
                    
                }
            }
            
            dottedLines.enumerated().forEach {
                
                let stateLabel = stateLabels[$0]
                
                $1.snp.makeConstraints { make in
                    make.top.equalToSuperview()
                    make.bottom.equalTo(stateColorsView.snp.bottom)
                    make.centerX.equalTo(stateLabel.snp.right)
                    make.width.equalTo(1.0)
                }
                
            }
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            markImageView.layoutIfNeeded()
            
            let multiplied = self.multiplied
            
            var left = multiplied * self.frame.width
            
            if left <= markImageView.frame.width/2.0 {
                left = 0
            } else if left > self.frame.width - markImageView.frame.width {
                
                left = self.frame.width - markImageView.frame.width
            } else {
                
                left = left - markImageView.frame.width/2.0
                
            }
            
            markImageView.snp.updateConstraints { make in
                
                if left == 0 {
                    make.left.equalToSuperview()
                } else {
                    make.left.equalToSuperview().offset(left)
                }
                
            }
            
        }
        
    }
    
}

//MARK: - DottedLine
extension HeartRateStateCell.HeartRateStateView {
    
    class DottedLine: View {
        
        let lineColor = UIColor.assist_FFFFFF
        
        let lineLayer = CAShapeLayer()
        
        
        override func makeUI() {
            super.makeUI()
            
            lineLayer.strokeColor = lineColor.cgColor
            lineLayer.frame = self.bounds
            lineLayer.lineWidth = 1.0
            lineLayer.lineDashPattern = [3.0, 3.0]
            
            layer.addSublayer(lineLayer)
            
        }
        
        var path: UIBezierPath {
            
            let path = UIBezierPath()
            path.move(to: CGPoint(x: self.bounds.midX, y: 0))
            path.addLine(to: CGPoint(x: self.bounds.midX, y: self.bounds.height))
            return path
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            
            lineLayer.frame = self.bounds
            lineLayer.path = path.cgPath
            
        }
        
    }
}

//MARK: - StateColorsView
extension HeartRateStateCell.HeartRateStateView {
    
    class StateColorsView: View {
        
        private let colors = UIColor.HeartRate.state
        private let locations: [NSNumber] = [0, 1]
        
        let colorsLayers = CAGradientLayer()
        
        override func makeUI() {
            super.makeUI()
            
            
            colorsLayers.colors = colors.map{ $0.cgColor }
            colorsLayers.locations = locations
            
            colorsLayers.startPoint = CGPoint(x: 0.25, y: 0.5)
            colorsLayers.endPoint = CGPoint(x: 0.75, y: 0.5)
            
            layer.addSublayer(colorsLayers)
        }
        
        override func layoutSubviews() {
            super.layoutSubviews()
            
            colorsLayers.frame = self.bounds
            
            colorsLayers.cornerRadius = self.bounds.height/2.0
        }
        
        
    }
    
    
}

